package com.yxy.chatserver.config;

import com.yxy.chatserver.handler.WebSocketHandshakeInterceptor;
import com.yxy.chatserver.handler.WebSocketServerHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;

/**
 * WebSocket配置类
 */
@Configuration
@EnableWebSocket
public class WebSocketConfiguration implements WebSocketConfigurer {

    @Autowired
    private WebSocketServerHandler webSocketServerHandler;
    
    @Autowired
    private WebSocketHandshakeInterceptor webSocketHandshakeInterceptor;

    /**
     * 注册WebSocket处理器
     * @param registry
     */
    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(webSocketServerHandler, "/chat") // 添加处理器
                .addInterceptors(webSocketHandshakeInterceptor) // 添加拦截器
                .setAllowedOriginPatterns("*"); // 允许跨域，使用patterns替代origins以支持带凭证的连接
//                .withSockJS(); // 启用SockJS协议支持  /// 刚开始因为启用了SockJS协议，而前端使用的WebSocket，导致协议错误
    }
}
